package top.yongyan0624.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import top.yongyan0624.common.lang.CodeMsg;
import top.yongyan0624.common.lang.ResultVO;
import top.yongyan0624.entity.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-05-22
 */
@RestController
public class QuestionController extends BaseController {

    @RequestMapping("/partyHistory/randomQuestion")
    public ResultVO question() {

        Question question = questionService.question();

        return ResultVO.success(question);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/queryQuestion")
    public ResultVO queryQuestion(@RequestParam Long pageNum, @RequestParam Long pageSize) {
        Page<Question> page = new Page<>(pageNum, pageSize);
        Page<Question> pageData = questionService.page(page, new QueryWrapper<>());
        for (Question question : pageData.getRecords()) {
            List<Answer> answerList = answerService.list(new QueryWrapper<Answer>().eq("question_id", question.getId()));
            Answer rightAnswer = answerService.getOne(new QueryWrapper<Answer>().eq("id", question.getRight()));
            String[] answers = answerList.stream().map(Answer::getContent).toArray(String[]::new);
            //将正确答案的数组下标写入
            for (int i = 0; i < answers.length; i++) {
                if (answers[i].equals(rightAnswer.getContent())) {
                    question.setRight((long) i);
                    break;
                }
            }
            question.setAnswer(answers);
        }

        return ResultVO.success(pageData);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/queryQuestionByContent")
    public ResultVO queryQuestionByContent(@RequestParam String content, @RequestParam Long pageNum, @RequestParam Long pageSize) {
        Page<Question> page = new Page<>(pageNum, pageSize);
        Page<Question> pageData = questionService.page(page, new QueryWrapper<Question>()
                .like(content != null && !content.equals(""), "content", content));
        for (Question question : pageData.getRecords()) {
            List<Answer> answerList = answerService.list(new QueryWrapper<Answer>().eq("question_id", question.getId()));
            Answer rightAnswer = answerService.getOne(new QueryWrapper<Answer>().eq("id", question.getRight()));
            String[] answers = answerList.stream().map(Answer::getContent).toArray(String[]::new);
            //将正确答案的数组下标写入
            for (int i = 0; i < answers.length; i++) {
                if (answers[i].equals(rightAnswer.getContent())) {
                    question.setRight((long) i);
                    break;
                }
            }
            question.setAnswer(answers);
        }
        return ResultVO.success(pageData);
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/addQuestion")
    public ResultVO addQuestion(@RequestBody Question question) {
        boolean ok = questionService.save(question);
        Question newQuestion = questionService.getOne(new QueryWrapper<Question>().eq("content", question.getContent()));

        String[] answerContent = question.getAnswer();
        for (int i = 0; i < answerContent.length; i++) {
            Answer answer = new Answer();
            answer.setContent(answerContent[i]);
            answer.setQuestionId(newQuestion.getId());

            answerService.save(answer);
            //保存答案后，判断是否为正确答案，进行处理
            if (i == question.getRight()) {
                Answer a = answerService.getOne(new QueryWrapper<Answer>().orderByDesc("id").last("limit 1"));
                newQuestion.setRight(a.getId());
                questionService.updateById(newQuestion);
            }
        }

        if (ok) {
            return ResultVO.success("新增成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！出错了，新增失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/delQuestion/{id}")
    public ResultVO delQuestion(@PathVariable Long id) {
        boolean ok = questionService.removeById(id);

        List<Answer> answerList = answerService.list(new QueryWrapper<Answer>().eq("question_id", id));
        List<Long> answerIds = answerList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        answerService.removeByIds(answerIds);

        if (ok) {
            return ResultVO.success("删除成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！出错了，删除失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @RequestMapping("/admin/delAllQuestion")
    public ResultVO delAllQuestion(@RequestBody MyList<Long> myList) {
        List<Long> ids = myList.getList();
        for (Long id : ids) {
            if (delQuestion(id).getCode() == 400) {
                return ResultVO.error(new CodeMsg("对不起！不存在这条题目:" + id + "，删除失败！"));
            }
        }
        return ResultVO.success("删除成功！");
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/updateQuestion")
    public ResultVO updateQuestion(@RequestBody Question question) {
        boolean ok = questionService.updateById(question);

        List<Answer> answerList = answerService.list(new QueryWrapper<Answer>().eq("question_id", question.getId()));
        List<Long> answerIds = answerList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        answerService.removeByIds(answerIds);

        String[] answerContent = question.getAnswer();
        for (int i = 0; i < answerContent.length; i++) {
            Answer answer = new Answer();
            answer.setContent(answerContent[i]);
            answer.setQuestionId(question.getId());

            answerService.save(answer);
            //保存答案后，判断是否为正确答案，进行处理
            if (i == question.getRight()) {
                Answer a = answerService.getOne(new QueryWrapper<Answer>().orderByDesc("id").last("limit 1"));
                question.setRight(a.getId());
                questionService.updateById(question);
            }
        }

        if (ok) {
            return ResultVO.success("修改成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！出错了，修改失败！"));
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @GetMapping("/admin/countQuestion")
    public ResultVO countQuestion() {
        return ResultVO.success("查询成功",questionService.count());
    }
}
